package com.tuling.code.spring;

import org.junit.Test;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.util.Assert;

public class BeanfactoryTest {
	
	@Test
	public void createBeanTest(){
		//Bean的创建
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		UserServiceImpl upl = factory.createBean(UserServiceImpl.class);
		System.out.println(upl);
		upl.delete();
	}
	
	@Test
	public void beanStore(){
		//Bean存储
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		factory.registerSingleton("dao", new UserDaoImpl());  //存储Bean
		//Bean获取
		UserDao dao = (UserDao) factory.getBean("dao");
		dao.save();
	}
	
	/**
	 * 依赖关系演示
	 */
	@Test
	public void dependcyTest(){
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		
		factory.registerSingleton("userDao", new UserDaoImpl());  //存储Bean
		
		//by type可以成功
		UserServiceImpl upl = (UserServiceImpl) factory.createBean(UserServiceImpl.class, 
				AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true);
		System.out.println(upl);
		upl.save();
		
		//by name  service中的userDao,属性名称必须预注册时的名称一致  registerSingleton("userDao", new UserDaoImpl())
		UserServiceImpl upl2 = (UserServiceImpl) factory.createBean(UserServiceImpl.class, 
				AbstractBeanDefinition.AUTOWIRE_BY_NAME, false);
		System.out.println(upl2);
		upl2.save();
	}
	
	/**
	 * BeanDefinition注册加载bean
	 */
	@Test
	public void beanDefinationTest(){
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
		reader.loadBeanDefinitions("spring.xml");
		UserServiceImpl bean = factory.getBean(UserServiceImpl.class);
		Assert.notNull(bean,"bean 不能为空");
		Assert.notNull(bean.getUserDao(),"UserDao 不能为空");
		bean.save();
	}
	
	@Test
	public void loadPluginTest(){
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
		reader.loadBeanDefinitions("plugin.xml");
		LogPlugin bean = factory.getBean(LogPlugin.class);
		Assert.notNull(bean,"bean 不能为空");
		
		//factory.removeBeanDefinition(beanName);
	}
}
